package com.ayf.payment.game.api.controller.paychannel;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.channel.jiabei.util.JbStringUtil;
import com.ayf.payment.game.api.dto.platform.PaymentChannelDTO;
import com.ayf.payment.game.api.entity.Order;
import com.ayf.payment.game.api.service.payment.huyu.util.HuYuSignUtil;
import com.ayf.payment.game.api.type.OrderStatus;
import com.ayf.payment.game.api.utils.HttpServletRequestUtil;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.ayf.payment.game.api.wx.WxSendMsgUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import com.swwx.charm.zookeeper.exception.GetLockFailedException;
import com.swwx.charm.zookeeper.exception.ReleaseLockFailedException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RequestMapping("/v/huyu/pay")
@RestController
public class HuYuPayNotifyController extends BasePayNotifyController {

    @Autowired
    private WxSendMsgUtils wxSendMsgUtils;

    private static final ExecutorService executorService = Executors.newCachedThreadPool();

    @RequestMapping("/notify")
    public void notify(HttpServletRequest request, HttpServletResponse response) {
        String orderno = JbStringUtil.formatString(request.getParameter("ordernumber"));
        super.notifyAsync(request,response,orderno);
    }

    /**
     * 代付异步通知处理
     */
    @RequestMapping("/paynotify")
    public void payNotify(HttpServletRequest request, HttpServletResponse response) {
        String orderno = JbStringUtil.formatString(request.getParameter("batchnumber"));
        super.agentPayNotifyAsync(request,response,orderno);
    }

    @RequestMapping("/returns")
    public void returns(HttpServletRequest request, HttpServletResponse response) {
        String orderno = JbStringUtil.formatString(request.getParameter("ordernumber"));
        super.notifySync(request,response,orderno);
    }

    @Override
    protected void notifyAsyncBusinesExec(HttpServletRequest request, HttpServletResponse response,Object obj) {
        PrintWriter pw = null;
        String traceId = SnowFlakeUtils.getTraceId();
        String orderno;
        String resCode = "ok";
        try {
            pw = response.getWriter();
            Map<String, String> reqParmMap = HttpServletRequestUtil.getRequestParameters(request);
            orderno = reqParmMap.get("ordernumber");
            LogPortal.info("{} 互娱交易异步通知 参数:{}", traceId,reqParmMap);
            if (StringUtils.isEmpty(orderno)) {
                LogPortal.info("{} 互娱交易异步通知 订单号数值为空，不进行后续操作", traceId);
                return;
            }
            Order order = orderService.selectByMerchantOrderNo(orderno);
            if (order == null) {
                LogPortal.error("{} 互娱交易异步通知 订单号[{}]在我方系统查询不到", traceId, orderno);
                return;
            }
            PaymentChannelDTO paymentChannelDTO = systemInitialization.channelDTO(order.getPayChannleId());
            String KeyValue = paymentChannelDTO.getChannelKey();

            Map<String, String> signMap = new LinkedHashMap<>();
            signMap.put("partner",paymentChannelDTO.getAccountNumber());
            signMap.put("ordernumber",reqParmMap.get("ordernumber"));
            signMap.put("orderstatus",reqParmMap.get("orderstatus"));
            signMap.put("paymoney",reqParmMap.get("paymoney"));
            String signVer = HuYuSignUtil.getSign(traceId,"互娱交易异步通知",signMap,KeyValue);
            // 1:支付成功，非1为支付失败
            String status = reqParmMap.get("orderstatus");
            OrderStatus orderStatus;
            if (reqParmMap.get("sign").equalsIgnoreCase(signVer.trim())) {
                String errMsg = "渠道异步通知返回失败";
                if ("1".equals(status)) {
                    orderStatus = OrderStatus.SUCCESS;
                } else {
                    orderStatus = OrderStatus.FAIL;
                }
                if (OrderStatus.PROCESSING.equals(order.getOrderStatus())) {
                    String XY_GAME_PAY_LOCK_FLAG= System.getenv("XY_GAME_PAY_LOCK_FLAG");
                    String orderLockName = "orderLock".concat(this.getClass().getSimpleName()).concat(XY_GAME_PAY_LOCK_FLAG).concat(orderno);
                    boolean orderLock=false;
                    try {
                        if (orderLock = distributedLock.getLock(orderLockName)) {
                            Order order2 = orderService.selectByMerchantOrderNo(orderno);
                            if (order2 != null && OrderStatus.PROCESSING.equals(order2.getOrderStatus())){
                                order.setOrderStatus(orderStatus);
                                order.setOrderNo(reqParmMap.get("sysnumber"));
                                JSONObject dataObject = new JSONObject();
                                if (OrderStatus.FAIL.equals(order.getOrderStatus())){
                                    dataObject.put("err_code",status);
                                    dataObject.put("err_code_desc",errMsg);
                                }
                                orderService.paymentOrder(order, dataObject);
                                if (OrderStatus.SUCCESS.equals(order.getOrderStatus())) {
                                    executorService.submit(new Runnable() {
                                        @Override
                                        public void run() {
                                            orderService.orderToGetWay(order);
                                            try {
                                                wxSendMsgUtils.rechargeSuccess(order);
                                            } catch (Exception e) {
                                                LogPortal.error("{} 互娱交易异步通知 商户订单号[{}]CallBack 微信通知异常", e, traceId, orderno);
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    } catch (GetLockFailedException e) {
                        LogPortal.error("{} >>> [DISTRIBUTED_LOCK_ACQUIRE_FAILED_ZK] 分布式锁获取失败,锁名称为:{}", orderno, orderLockName);
                        LogPortal.error("{} >>> {} 获取lock失败", e, orderno, orderLockName);
                    } catch (Exception e) {
                        LogPortal.error("{} >>> {} 任务执行出错 ", e, orderno, orderLockName);
                    } finally {
                        if (orderLock) {
                            LogPortal.info(orderno + " >>> " + orderLockName + " finished.");
                            try {
                                distributedLock.releaseLock(orderLockName);
                            } catch (ReleaseLockFailedException e) {
                                LogPortal.error("{} >>> [DISTRIBUTED_LOCK_RELEASE_FAILED_ZK] 分布式锁释放失败,锁名称为:{}",orderno, orderLockName);
                                LogPortal.error("{} >>> {} 释放失败", e,orderno, orderLockName);
                            }
                        }
                    }
                } else {
                    LogPortal.info("{} 互娱交易异步通知 商户订单号[{}] 异步通知 不在更新订单状态：[{}]", traceId, orderno, order.getOrderStatus());
                }
            } else {
                LogPortal.error("{} 互娱交易异步通知 商户订单号[{}] 异步通知验签失败", traceId, orderno);
            }
        } catch (Exception e) {
            LogPortal.error("{} 互娱交易异步通知 验签业务逻辑处理失败，具体原因:{}", e, traceId, e.getMessage());
        } finally {
            pw.write(resCode);
            pw.flush();
            if (pw != null)
                pw.close();
        }
    }

    @Override
    protected void notifySyncBusinesExec(HttpServletRequest request, HttpServletResponse response) {
        String orderno = JbStringUtil.formatString(request.getParameter("ordernumber"));
        try {
            String attach = JbStringUtil.formatString(request.getParameter("attach"));
            response.sendRedirect(attach + "/gws/loading.html?orderNo=" + orderno);
        } catch (Exception e) {
            LogPortal.error("订单号:{} 互娱交易同步通知 发生{}异常",e,orderno,e.getClass().getName());
        }
    }

    @Override
    protected void agentPayNotifyAsyncBusinesExec(HttpServletRequest request, HttpServletResponse response, Object obj) {
        String traceId = SnowFlakeUtils.getTraceId();
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            Map<String, String> reqParmMap = HttpServletRequestUtil.getRequestParameters(request);
            LogPortal.info("{} 互娱代付异步通知 参数:{}", traceId,reqParmMap);
            String orderno = reqParmMap.get("batchnumber");
            if (StringUtils.isEmpty(orderno)){
                LogPortal.info("{} 互娱代付异步通知 商户订单号数值为空，不进行后续操作",traceId);
                return;
            }
            if (orderno.startsWith("Y")) {
                merchantCashOutService.huYuPaymentOnBehalfOf(traceId,reqParmMap);
            } else {
                merchantPayOrderService.huYuPayNotify(traceId, reqParmMap);
            }
            pw.write("ok");
            pw.flush();
        } catch (Exception e) {
            LogPortal.error("{} 互娱代付异步通知 业务逻辑处理失败，具体原因:{}", e, traceId, e.getMessage());
            pw.write("互娱代付异步通知 业务逻辑处理失败：" + e.getMessage());
            pw.flush();
        } finally {
            if (pw != null)
                pw.close();
        }
    }
}
